<?php

namespace App\Http\Controllers\Member;

use App\Exports\DomainInduce\Info;
use App\Http\Controllers\Controller;
use App\Jobs\ExcelImport;
use App\Models\Domain\Induce\Condition;
use App\Models\Domain\Induce\ExcelQueue;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Schema;


class DomainInduceController extends Controller {

    public function uploadExcel() {
        $request = request();
        if (!$request->hasFile('file')) {
            $result = [
                'code' => 400,
                'msg' => "上传失败!",
                'data' => null,
            ];

            return response()->json($result);
        }
        $getClientOriginalExtension = $request->file('file')->getClientOriginalExtension();

        $path = $request->file('file')->storeAs('upload/excel', 'import.'.$getClientOriginalExtension, 'public');
        if ($path) {
            $result = [
                'code' => 0,
                'msg' => "success",
                'data' => ['url' => '/storage/'.$path],
            ];
            return response()->json($result);
        } else {
            $result = [
                'code' => 400,
                'msg' => "保存失败!",
                'data' => null,
            ];
            return response()->json($result);
        }

    }
    public function export() {

      //  return (new Info())->download('domain.xlsx');
          (new Info)->store('domain.xlsx')->onQueue('manager_export');
        //  (new Info)->store('domain.xlsx');

    }
    public function import() {
        $excel_queue = ExcelQueue::where('queue_name', '域名归纳')
            ->where('type', 1)
            ->where('status', false)
            ->get();

        if ($excel_queue->count() > 0) {
            return '有未完成任务 请稍后尝试...';
        }

        //初始化进度
        $excel_queue = ExcelQueue::updateOrCreate([
            'queue_name' => '域名归纳',
        ], [
            'type' => 1,
            'status' => false,
            //  'status' => true,
            'total_chunk' => 100,
            'current_chunk' => 0,
            'remarks' => '',
        ]);

        if (!\Storage::exists('public/upload/excel/import.xlsx')) {
            $excel_queue->remarks = '文件不存在';
            $excel_queue->status = true;
            $excel_queue->save();
            return '请先上传文件';
        }


        $res = dispatch(new ExcelImport());
        if ($res) {
            return '提交成功';
        } else {
            $excel_queue->remarks = '提交失败';
            $excel_queue->status = true;
            $excel_queue->save();
            return '提交失败';
        }
    }


    public function import_status() {
        $excel_queue = ExcelQueue::where('queue_name', '域名归纳')
            ->where('type', 1)
            ->first();

        if ($excel_queue->status == true) {
            //完成
            return $excel_queue->remarks;
        }
        //  $last_time = $excel_queue->updated_at->addMinutes(3);
        $last_time = $excel_queue->updated_at->addSeconds(180);
        if (Carbon::now()->gt($last_time)) {
            //超时 10分钟
            $excel_queue = ExcelQueue::updateOrCreate([
                'queue_name' => '域名归纳',
            ], [
                'status' => true,
                'remarks' => '超时',
            ]);
            //超时
            return '块'.$excel_queue->remarks;
        }
        $percent = $excel_queue->current_chunk / ($excel_queue->total_chunk / 100);
        $percent = number_format($percent, 2).'%';
        $res = '</br>'.'最后更新:'.$excel_queue->updated_at.'</br>'.'</br>'.
            '完 成 率:'.$percent.'</br>'.'</br>'.
            '信息:'.$excel_queue->remarks.'</br>'.'</br>'.
            '<div><a style="background-color: #00a148;color: white;float: right;margin-right: 20px;padding: 10px" onclick="window.location.reload()">刷新</a></div>';

        return $res;

    }

    public function index(Request $request) {
        $group_name = '前端';
        $get_keys = $this->get_show_key($group_name, 'key', false);

        if ($request->isMethod('POST')) {

            $value = $request->get('value');
            //  $page = $request->get('page');
            $limit = $request->get('limit', 10);
            $data = \App\Models\Domain\Induce\Info::where(
                function ($query) use ($value) {
                    $query->where('domain', 'like', '%'.$value.'%')
                        ->orWhere('id', $value);
                }
            )
                ->select($get_keys)
                ->paginate($limit);
            $count = $data->total();
            if ($data) {
                return response()->json(
                    [
                        'code' => 0,
                        'msg' => 'ok',
                        'count' => $count,
                        'data' => $data,
                    ]
                );
            } else {
                return $this->result_api(200, 'list error');
            }
        }
        $key_name = collect($this->get_show_key($group_name, 'key_name', false));
        $key_name = $key_name->sortBy('sort')->values()->all();

        $data = \App\Models\Domain\Induce\Info::select($get_keys)->paginate(50);

        //  dd($key_name);

        return view('public.search_base', compact('key_name', 'data'));
    }

    public function induce(Request $request) {

        $group_name = $request->get('group_name', '后端');
        if ($request->isMethod('POST')) {
            $input_data = $request->get('data');

            $limit = $request->get('limit', 10);
            $data = [];

            if (!isset($input_data)) {
                $data = \App\Models\Domain\Induce\Info::select($this->get_show_key($group_name,
                    'key'))->paginate($limit);
            } else {
                $data = \App\Models\Domain\Induce\Info::
                when(isset($input_data), function ($query) use ($input_data) {
                    $search_data = [];
                    foreach ($input_data as $k1 => $v1) {
                        if (isset($input_data[$k1])) {
                            //日期比较
                            if (strpos($k1, '__date')) {
                                $cols_name = str_replace('__date', '', $k1);
                                $explode = explode(' - ', $v1);
                                $search_data[] = [$cols_name, '>=', $explode[0],];
                                $search_data[] = [$cols_name, '<=', $explode[1],];
                                continue;
                            }
                            //数值范围比较
                            if (strpos($k1, '_min')) {
                                $cols_name = str_replace('_min', '', $k1);
                                $search_data[] = [$cols_name, '>=', $v1,];
                                continue;
                            }
                            if (strpos($k1, '_max')) {
                                $cols_name = str_replace('_max', '', $k1);
                                $search_data[] = [$cols_name, '<=', $v1,];
                                continue;
                            }
                            if ($k1 == 'domain') {
                                $search_data[] = [$k1, 'like', '%'.$v1.'%',];
                                continue;
                            }
                            // 等于比较
                            $search_data[] = [$k1, '=', $v1,];
                        }
                    }
// dump($search_data);
                    return $query->where($search_data);
                })
                    ->select($this->get_show_key($group_name, 'key'))
                    ->paginate($limit);
            }

            //   dd($data);
            $count = $data->total();
            if ($data) {
                return response()->json(
                    [
                        'code' => 0,
                        'msg' => 'ok',
                        'count' => $count,
                        'data' => $data,
                    ]
                );
            } else {
                return $this->result_api(200, 'list error');
            }
        }
        $key_name = collect($this->get_show_key($group_name, 'key_name'));

        $key_name = $key_name->sortBy('sort')->values()->all();
        $condition_name = Condition::get(['name', 'back_end'])->unique('name');

        //  dd($key_name);
        return view('manager.manager.domain_induce', compact('key_name', 'condition_name'));
    }

    public function induce_save(Request $request) {
        $input_data = $request->get('data');
        $is_save = \App\Models\Domain\Induce\Info::where('id', $input_data['id'])->update(array_diff_key($input_data,
            ['id' => 'ID值']));
        if ($is_save) {
            return $this->result_api(200, 'success');
        } else {
            return $this->result_api(200, 'list error');
        }
    }

    public function condition(Request $request) {

        if ($request->isMethod('POST')) {
            //$table_name = $request->get('table');
            $table_key_name = DB::table('domain_induce_key_name')->get();
            $table_name = 'domain_induce_info';
            $group_name = $request->get('group_name', '后端');
            $back_end = $request->get('back_end');
            $condition = Condition::orderby('sort', 'DESC')->where(
                'table',
                $table_name
            )->where(
                'name',
                'like',
                '%'.$group_name.'%'
            )->get();

            $current_table = $table_key_name->where('table', $table_name);
            $data = [];

            foreach ($current_table as $key => $item) {
                $date_temp = [
                    "name" => $group_name,
                    "table" => $table_name,
                    "table_name" => $item->table_name,
                    "key" => $item->key,
                    "key_name" => $item->name,
                    "show" => 0,
                    "back_end" => $back_end,
                    "width" => 100,
                    "show_value" => '',
                    "sort" => 50,
                ];
                foreach ($condition as $condition_item) {
                    if ($item->key == $condition_item->key) {
                        // dump($condtion_item);
                        $date_temp['show'] = $condition_item->show;
                        $date_temp['back_end'] = $condition_item->back_end;
                        $date_temp['width'] = $condition_item->width;
                        $date_temp['show_value'] = $condition_item->show_value;
                        $date_temp['sort'] = $condition_item->sort;
                    }
                }
                $data[] = $date_temp;
            }
            $data = collect($data);
            $data = $data->sortBy('sort',);
            $data = $data->values()->all();
            $count = count($data);

            if ($data) {
                return response()->json(
                    [
                        'code' => 0,
                        'msg' => 'ok',
                        'count' => $count,
                        'data' => $data,
                    ]
                );
            } else {
                return $this->result_api(200, 'list error');
            }
        }
        $condition_name = Condition::get(['name', 'back_end'])->unique('name');

        return view(
            'manager.manager.domain_induce_condition',
            compact('condition_name')
        );
    }

    public function condition_create(Request $request) {
        $group_name = $request->get('group_name');
        $back_end = $request->get('back_end');
        DB::beginTransaction();
        try {
            Condition::updateOrCreate(
                [
                    'name' => $group_name,
                    'table' => 'domain_induce_info',
                    'key' => 'id',
                ],
                [
                    'show' => true,
                    'back_end' => $back_end,
                    'width' => 70,
                    'show_value' => '',
                    'sort' => -128,
                ]
            );
            Condition::updateOrCreate(
                [
                    'name' => $group_name,
                    'table' => 'domain_induce_info',
                    'key' => 'domain',
                ],
                [
                    'show' => true,
                    'back_end' => $back_end,
                    'width' => 200,
                    'show_value' => '',
                    'sort' => -127,
                ]
            );
            DB::commit();
            return $this->result_api(200, 'success');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->result_api(200, 'create error');
        }

    }

    public function condition_del(Request $request) {
        $group_name = $request->get('group_name');
        $is_del = Condition::where('name', $group_name)->delete();
        if ($is_del) {
            return $this->result_api(200, 'success');
        } else {
            return $this->result_api(200, 'delete error');
        }
    }

    public function condition_save(Request $request) {
        $input_data = $request->get('data');
        $data = collect($input_data);
        $data = $data->except('table_name', 'key_name');
        $is_create = Condition::updateOrCreate(
            [
                'name' => $data['name'],
                'table' => $data['table'],
                'key' => $data['key'],
            ],
            [
                'show' => $data['show'],
                'back_end' => $data['back_end'],
                'width' => $data['width'],
                'show_value' => is_null($data['show_value']) ? ''
                    : $data['show_value'],
                'sort' => $data['sort'],
            ]
        );
        if ($is_create) {
            return $this->result_api(200, 'success');
        } else {
            return $this->result_api(200, 'list error');
        }
    }

    public function initKeyName() {
        //所有表
        $tables = [
            'domain_induce_info' => '基本详情',
            //            'domain_induce_icp'     => '备案详情',
            //            'domain_induce_baidu'   => '百度板块',
            //            'domain_induce_360'     => '360板块',
            //            'domain_induce_news'    => '新闻源板块',
            //            'domain_induce_old'     => '历史白块',
            //            'domain_induce_sougou'  => '搜狗板块',
            //            'domain_induce_testing' => '拦截板块',
        ];
        //所有键名
        $key_names = [
            'domain_induce_info' => [
                'domain' => '域名',
                'self_self' => '自持',
                'self_price' => '成本',

                'testing_qq' => 'QQ检测',
                'testing_wechat' => '微信检测',
                'testing_condition' => '被墙/污染',

                'sougou_shourushu' => '搜狗收录/污染',
                'sougou_title' => '搜狗标题',
                'sougou_describe' => '搜狗描述',
                'sougou_snapshot' => '快照时间',
                'sougou_pr_old' => '搜狗PR【历史】',
                'sougou_re_link' => '搜狗反链',
                'sougou_official' => '搜狗官网',
                'sougou_news_source' => '新闻源',

                'old_age' => '年龄',
                'old_count' => '数量',
                'old_last' => '最老',
                'old_new' => '最新',
                'old_chines' => '中文',
                'old_percent' => '占比',
                'old_unified_percent' => '统一度',
                'old_year_5' => '五年建站',
                'old_language' => '语言',
                'old_label' => '标记',
                'old_keyword' => '关键词',
                'old_year_sort' => '年排序',
                'old_title' => '标题',
                'old_remarks' => '历史备注',

                'icp_company' => '单位名称',
                'icp_type' => '单位性质',
                'icp_num' => 'ICP备案号',
                'icp_region' => '备案地区',
                'icp_site_name' => '网站名称',
                'icp_audit_time' => '审核时间',
                'icp_provider' => '接入商',
                'icp_status' => '状态',
                'icp_blacklist' => '备案黑名单',
                'icp_police' => '备案地公安机关',
                'icp_multi' => '批量备案',

                'base_delete_type' => '删除类型',
                'base_delete_day' => '删除日期',
                'base_suffix' => '后缀',
                'base_email' => '邮箱',
                'base_people' => '注册人',
                'base_registrant' => '注册商',
                'base_reg_day' => '注册时间',
                'base_end_day' => '到期时间',
                'base_reg_age' => '注册年龄',
                'base_old' => '是否老域名',
                'base_available_day' => '可用天数',
                'base_status' => '域名状态',

                'baidu_included' => '百度收录量',
                'baidu_grey' => '百度灰',
                'baidu_safe' => '百度安全',
                'baidu_official' => '百度官网',
                'baidu_v_log' => '百度V认证',
                'baidu_evaluate' => '百度评价',
                'baidu_weight' => '百度权重',
                'baidu_re_link' => '百度反链',
                'baidu_testing' => '百度检测',
                'baidu_re_amount' => '反向链接数量',
                'baidu_high_weight_5' => '高权重5+',
                'baidu_gov' => 'Gov外链',

                '360_included' => '360收录',
                '360_weight' => '360权重',
                '360_official' => '360官网',
            ],
        ];

        //初始化键名
        $data = [];
        foreach ($tables as $table => $table_item) {
            $columns = Schema::getColumnListing($table); //字段名
            foreach ($columns as $item) {
//                if ($item == 'id' || $item == 'domain') {
//                    continue;
//                }
                $data[] = [
                    'table' => $table,
                    'table_name' => $table_item,
                    'key' => $item,
                    'name' => $key_names[$table][$item] ?? $item,
                ];
            }
        }
        DB::table('domain_induce_key_name')->truncate();
        $res = DB::table('domain_induce_key_name')->insert($data);

        return $res;
    }

    private function get_show_key($group_name, $type = 'key', $back_end = true) {
        $table_key_name = DB::table('domain_induce_key_name')->get();

        $condition = Condition::orderby('sort', 'DESC')
            ->where('name', 'like', '%'.$group_name.'%')
            ->where('back_end', $back_end)
            ->get();
        //init condition DB
        if (count($condition) == 0) {
            Condition::updateOrCreate([
                'name' => '前端',
                'table' => 'domain_induce_info',
                'key' => 'id',
            ],
                [
                    'show' => true,
                    'width' => 70,
                    'show_value' => '',
                    'back_end' => false,
                    'sort' => -128,
                ]);
            Condition::updateOrCreate([
                'name' => '前端',
                'table' => 'domain_induce_info',
                'key' => 'domain',
            ],
                [
                    'show' => true,
                    'width' => 200,
                    'show_value' => '',
                    'back_end' => false,
                    'sort' => -127,
                ]);
            Condition::updateOrCreate([
                'name' => '后端',
                'table' => 'domain_induce_info',
                'key' => 'id',
            ],
                [
                    'show' => true,
                    'width' => 70,
                    'show_value' => '',
                    'back_end' => true,
                    'sort' => -128,
                ]);
            Condition::updateOrCreate([
                'name' => '后端',
                'table' => 'domain_induce_info',
                'key' => 'domain',
            ],
                [
                    'show' => true,
                    'width' => 200,
                    'show_value' => '',
                    'back_end' => true,
                    'sort' => -127,
                ]);

            return self::get_show_key($group_name, $type);
        }
        $data = [];
        foreach ($table_key_name as $key => $item) {
            foreach ($condition as $condtion_item) {
                if ($item->key == $condtion_item->key && $condtion_item->show == true) {
                    if ($type == 'key') {
                        $data[] = $condtion_item->key;
                    } else {
                        $temp_data = [
                            'name' => $item->name,
                            'key' => $condtion_item->key,
                            'width' => $condtion_item->width,
                            'sort' => $condtion_item->sort,
                        ];

                        $data[] = $temp_data;
                    }
                }
            }
        }


        return $data;
    }


}
